<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

	<meta name="baidu-site-verification" content="IwHYiEzBBM" />



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />










  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="android," />





  <link rel="alternate" href="/atom.xml" title="长孙雨聪--七星上将" type="application/atom+xml" />






<meta name="description" content="前言这篇文章主要讲解view的工作原理中的三大流程，包括测量流程，布局流程，绘制流程。这些都是自定义控件的基础。下面先对三大流程的职责做简要的概述： 测量流程确定了控件的测量的大小；布局流程确定了控件在父控件中的四个位置的坐标和控件的实际大小；绘制流程负责控件的绘制并显示在屏幕上。 view的绘制流程是从哪里开始的？V">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Androiod中View的工作原理">
<meta property="og:url" content="http://zhangsunyucong.top/2018/01/15/view-meassure/index.html">
<meta property="og:site_name" content="长孙雨聪--七星上将">
<meta property="og:description" content="前言这篇文章主要讲解view的工作原理中的三大流程，包括测量流程，布局流程，绘制流程。这些都是自定义控件的基础。下面先对三大流程的职责做简要的概述： 测量流程确定了控件的测量的大小；布局流程确定了控件在父控件中的四个位置的坐标和控件的实际大小；绘制流程负责控件的绘制并显示在屏幕上。 view的绘制流程是从哪里开始的？View的绘制流程是从ViewRoot的performTraversals开始的">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-23T07:52:31.908Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Androiod中View的工作原理">
<meta name="twitter:description" content="前言这篇文章主要讲解view的工作原理中的三大流程，包括测量流程，布局流程，绘制流程。这些都是自定义控件的基础。下面先对三大流程的职责做简要的概述： 测量流程确定了控件的测量的大小；布局流程确定了控件在父控件中的四个位置的坐标和控件的实际大小；绘制流程负责控件的绘制并显示在屏幕上。 view的绘制流程是从哪里开始的？View的绘制流程是从ViewRoot的performTraversals开始的">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zhangsunyucong.top/2018/01/15/view-meassure/"/>





  <title>Androiod中View的工作原理 | 长孙雨聪--七星上将</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
	
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">长孙雨聪--七星上将</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">坚持不懈，必有回响。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-github">
          <a href="https://github.com/zhangsunyucong?tab=repositories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            Github
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
  
     

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsunyucong.top/2018/01/15/view-meassure/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="长孙雨聪--七星上将">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/myphoto.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="长孙雨聪--七星上将">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Androiod中View的工作原理</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-15T15:14:46+08:00">
                2018-01-15
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-01-23T15:52:31+08:00">
                2018-01-23
              </time>
            
          </span>

          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2018/01/15/view-meassure/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2018/01/15/view-meassure/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2018/01/15/view-meassure/" class="leancloud_visitors" data-flag-title="Androiod中View的工作原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,202字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  17分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><hr>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>这篇文章主要讲解view的工作原理中的三大流程，包括测量流程，布局流程，绘制流程。这些都是自定义控件的基础。下面先对三大流程的职责做简要的概述：</p>
<p>测量流程确定了控件的测量的大小；<br>布局流程确定了控件在父控件中的四个位置的坐标和控件的实际大小；<br>绘制流程负责控件的绘制并显示在屏幕上。</p>
<h3 id="view的绘制流程是从哪里开始的？"><a href="#view的绘制流程是从哪里开始的？" class="headerlink" title="view的绘制流程是从哪里开始的？"></a>view的绘制流程是从哪里开始的？</h3><p>View的绘制流程是从ViewRoot的performTraversals开始的。在performTraversals经过一堆的逻辑，会分别调用performMeasure，performLayout，performDraw。<br>然后在view树中，先后调用一下的方法：<br><a id="more"></a><br>performMeasure，measure onMeasure<br>performLayout，layout, onLayout<br>performDraw, draw, onDraw, dispatchDraw(绘制子view)</p>
<p>ViewRoot的实现类是ViewRootImpl，在ActivityThread中创建。</p>
<h3 id="MeasureSpec"><a href="#MeasureSpec" class="headerlink" title="MeasureSpec"></a>MeasureSpec</h3><p>MeasureSpec是view的测量规格，是一个int数值。在java中的int是32位的，所以MeasureSpec可以利用32位的一个数值来表示view的大少size和规格mode。在ViewRootImpl.java中提供了MeasureSpec组合和分解的方法。MeasureSpec是ViewRootImpl.java中的一个公开静态内部类，源码如下：</p>
<p>ViewRootImpl#MeasureSpec</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">public static class MeasureSpec &#123;</span><br><span class="line">    private static final int MODE_SHIFT = 30;</span><br><span class="line">    private static final int MODE_MASK  = 0x3 &lt;&lt; MODE_SHIFT;</span><br><span class="line"></span><br><span class="line">    /** @hide */</span><br><span class="line">    @IntDef(&#123;UNSPECIFIED, EXACTLY, AT_MOST&#125;)</span><br><span class="line">    @Retention(RetentionPolicy.SOURCE)</span><br><span class="line">    public @interface MeasureSpecMode &#123;&#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Measure specification mode: The parent has not imposed any constraint</span><br><span class="line">     * on the child. It can be whatever size it wants.</span><br><span class="line">     */</span><br><span class="line">    public static final int UNSPECIFIED = 0 &lt;&lt; MODE_SHIFT;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Measure specification mode: The parent has determined an exact size</span><br><span class="line">     * for the child. The child is going to be given those bounds regardless</span><br><span class="line">     * of how big it wants to be.</span><br><span class="line">     */</span><br><span class="line">    public static final int EXACTLY     = 1 &lt;&lt; MODE_SHIFT;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Measure specification mode: The child can be as large as it wants up</span><br><span class="line">     * to the specified size.</span><br><span class="line">     */</span><br><span class="line">    public static final int AT_MOST     = 2 &lt;&lt; MODE_SHIFT;</span><br><span class="line"></span><br><span class="line">    public static int makeMeasureSpec(@IntRange(from = 0, to = (1 &lt;&lt; MeasureSpec.MODE_SHIFT) - 1) int size,</span><br><span class="line">                                      @MeasureSpecMode int mode) &#123;</span><br><span class="line">        if (sUseBrokenMakeMeasureSpec) &#123;</span><br><span class="line">            return size + mode;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            return (size &amp; ~MODE_MASK) | (mode &amp; MODE_MASK);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    ...</span><br><span class="line">    </span><br><span class="line">    @MeasureSpecMode</span><br><span class="line">    public static int getMode(int measureSpec) &#123;</span><br><span class="line">        //noinspection ResourceType</span><br><span class="line">        return (measureSpec &amp; MODE_MASK);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static int getSize(int measureSpec) &#123;</span><br><span class="line">        return (measureSpec &amp; ~MODE_MASK);</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在上面，MODE_SHIFT为什么是30？因为它是使用高2位表示mode，低30为表示size。<br>MODE_MASK为0x3，二进制表示是<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0000 0000 0000 0000 0000 0000 0000 0011</span><br></pre></td></tr></table></figure></p>
<p>它左移30位后为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1100 0000 0000 0000 0000 0000 0000 0000</span><br></pre></td></tr></table></figure></p>
<p>由MODE_MASK理解组合makeMeasureSpec中的(size &amp; ~MODE_MASK) | (mode &amp; MODE_MASK)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">size &amp; ~MODE_MASK，就是</span><br><span class="line"></span><br><span class="line">size &amp; ~MODE_MASK = size &amp; 0011 1111 1111 1111 1111 1111 1111 1111</span><br><span class="line"></span><br><span class="line">当size=32时，</span><br><span class="line">100000 &amp; ~MODE_MASK = 100000 &amp; 0011 1111 1111 1111 1111 1111 1111 1111 = 0000 0000 0000 0000 0000 0000 0010 0000 = 32</span><br><span class="line"></span><br><span class="line">同理可知mode</span><br><span class="line"></span><br><span class="line">最后做与运算，将它们相加</span><br></pre></td></tr></table></figure>
<p>从源码中可以看出，mode有UNSPECIFIED，EXACTLY，AT_MOST。其中UNSPECIFIED等于0，AT_MOST是小于0，EXACTLY等于0。</p>
<h3 id="MeasureSpec的创建和测量流程"><a href="#MeasureSpec的创建和测量流程" class="headerlink" title="MeasureSpec的创建和测量流程"></a>MeasureSpec的创建和测量流程</h3><p>MeasureSpec是由父容器的约束和布局参数LayoutParams共同决定的。它在DecorView和普通view中创建也是不一样的。DecorView的父容器是Window，所以DecorView的MeasureSpec由窗口大小和布局参数共同决定的。普通view是由父容器的MeasureSpec和布局参数共同决定的。</p>
<p>（1）在DecorView中</p>
<p>ViewRootImpl#measureHierarchy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);</span><br><span class="line">childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">ViewRootImpl#getRootMeasureSpec</span><br><span class="line">private static int getRootMeasureSpec(int windowSize, int rootDimension) &#123;</span><br><span class="line">        int measureSpec;</span><br><span class="line">        switch (rootDimension) &#123;</span><br><span class="line"></span><br><span class="line">        case ViewGroup.LayoutParams.MATCH_PARENT:</span><br><span class="line">            // Window can&apos;t resize. Force root view to be windowSize.</span><br><span class="line">            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);</span><br><span class="line">            break;</span><br><span class="line">        case ViewGroup.LayoutParams.WRAP_CONTENT:</span><br><span class="line">            // Window can resize. Set max size for root view.</span><br><span class="line">            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);</span><br><span class="line">            break;</span><br><span class="line">        default:</span><br><span class="line">            // Window wants to be an exact size. Force root view to be that size.</span><br><span class="line">            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);</span><br><span class="line">            break;</span><br><span class="line">        &#125;</span><br><span class="line">        return measureSpec;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>当view设置MATCH_PARENT时，measureSpec的mode是MeasureSpec.EXACTLY，size是windowSize窗口大小。<br>当view设置WRAP_CONTENT时，measureSpec的mode是MeasureSpec.AT_MOST，size是windowSize窗口大小。<br>当view设置具体大小时，measureSpec的mode是MeasureSpec.EXACTLY，size是view设置的具体大小。</p>
<p>（2）在普通view中</p>
<p>ViewGroup#measureChildWithMargins</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">protected void measureChildWithMargins(View child,</span><br><span class="line">            int parentWidthMeasureSpec, int widthUsed,</span><br><span class="line">            int parentHeightMeasureSpec, int heightUsed) &#123;</span><br><span class="line">        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();</span><br><span class="line"></span><br><span class="line">        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,</span><br><span class="line">                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin</span><br><span class="line">                        + widthUsed, lp.width);</span><br><span class="line">        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,</span><br><span class="line">                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin</span><br><span class="line">                        + heightUsed, lp.height);</span><br><span class="line"></span><br><span class="line">        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>在ViewGroup#getChildMeasureSpec<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line">public static int getChildMeasureSpec(int spec, int padding, int childDimension) &#123;</span><br><span class="line">        int specMode = MeasureSpec.getMode(spec);</span><br><span class="line">        int specSize = MeasureSpec.getSize(spec);</span><br><span class="line"></span><br><span class="line">        int size = Math.max(0, specSize - padding);</span><br><span class="line"></span><br><span class="line">        int resultSize = 0;</span><br><span class="line">        int resultMode = 0;</span><br><span class="line"></span><br><span class="line">        switch (specMode) &#123;</span><br><span class="line">        // Parent has imposed an exact size on us</span><br><span class="line">        case MeasureSpec.EXACTLY:</span><br><span class="line">            if (childDimension &gt;= 0) &#123;</span><br><span class="line">                resultSize = childDimension;</span><br><span class="line">                resultMode = MeasureSpec.EXACTLY;</span><br><span class="line">            &#125; else if (childDimension == LayoutParams.MATCH_PARENT) &#123;</span><br><span class="line">                // Child wants to be our size. So be it.</span><br><span class="line">                resultSize = size;</span><br><span class="line">                resultMode = MeasureSpec.EXACTLY;</span><br><span class="line">            &#125; else if (childDimension == LayoutParams.WRAP_CONTENT) &#123;</span><br><span class="line">                // Child wants to determine its own size. It can&apos;t be</span><br><span class="line">                // bigger than us.</span><br><span class="line">                resultSize = size;</span><br><span class="line">                resultMode = MeasureSpec.AT_MOST;</span><br><span class="line">            &#125;</span><br><span class="line">            break;</span><br><span class="line"></span><br><span class="line">        // Parent has imposed a maximum size on us</span><br><span class="line">        case MeasureSpec.AT_MOST:</span><br><span class="line">            if (childDimension &gt;= 0) &#123;</span><br><span class="line">                // Child wants a specific size... so be it</span><br><span class="line">                resultSize = childDimension;</span><br><span class="line">                resultMode = MeasureSpec.EXACTLY;</span><br><span class="line">            &#125; else if (childDimension == LayoutParams.MATCH_PARENT) &#123;</span><br><span class="line">                // Child wants to be our size, but our size is not fixed.</span><br><span class="line">                // Constrain child to not be bigger than us.</span><br><span class="line">                resultSize = size;</span><br><span class="line">                resultMode = MeasureSpec.AT_MOST;</span><br><span class="line">            &#125; else if (childDimension == LayoutParams.WRAP_CONTENT) &#123;</span><br><span class="line">                // Child wants to determine its own size. It can&apos;t be</span><br><span class="line">                // bigger than us.</span><br><span class="line">                resultSize = size;</span><br><span class="line">                resultMode = MeasureSpec.AT_MOST;</span><br><span class="line">            &#125;</span><br><span class="line">            break;</span><br><span class="line"></span><br><span class="line">        // Parent asked to see how big we want to be</span><br><span class="line">        case MeasureSpec.UNSPECIFIED:</span><br><span class="line">            if (childDimension &gt;= 0) &#123;</span><br><span class="line">                // Child wants a specific size... let him have it</span><br><span class="line">                resultSize = childDimension;</span><br><span class="line">                resultMode = MeasureSpec.EXACTLY;</span><br><span class="line">            &#125; else if (childDimension == LayoutParams.MATCH_PARENT) &#123;</span><br><span class="line">                // Child wants to be our size... find out how big it should</span><br><span class="line">                // be</span><br><span class="line">                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;</span><br><span class="line">                resultMode = MeasureSpec.UNSPECIFIED;</span><br><span class="line">            &#125; else if (childDimension == LayoutParams.WRAP_CONTENT) &#123;</span><br><span class="line">                // Child wants to determine its own size.... find out how</span><br><span class="line">                // big it should be</span><br><span class="line">                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;</span><br><span class="line">                resultMode = MeasureSpec.UNSPECIFIED;</span><br><span class="line">            &#125;</span><br><span class="line">            break;</span><br><span class="line">        &#125;</span><br><span class="line">        //noinspection ResourceType</span><br><span class="line">        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>在getChildMeasureSpec中列出了在父容器MeasureSpec和view的布局参数下创建MeasureSpec的各种情况。得到MeasureSpec后，在measureChildWithMargins中将它传递给child的measure方法。在measure方法再传给onMeasure方法。这就是onMeasure方法中两个参数的来源。</p>
<p>View#onMeasure</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),</span><br><span class="line">                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>View#setMeasuredDimension中会调用setMeasuredDimensionRaw方法<br>View#setMeasuredDimensionRaw<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) &#123;</span><br><span class="line">        mMeasuredWidth = measuredWidth;</span><br><span class="line">        mMeasuredHeight = measuredHeight;</span><br><span class="line"></span><br><span class="line">        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>到这里就已经确定的view测量的大小。通过getMeasuredWidth()和getMeasuredHeight()就可以得到它们的值。</p>
<p>View#getSuggestedMinimumWidth<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">protected int getSuggestedMinimumWidth() &#123;</span><br><span class="line">        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>这里是说，控件是否设置了背景和最小大小。对应于android:background和android:minWidth。</p>
<p>View#getDefaultSize<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public static int getDefaultSize(int size, int measureSpec) &#123;</span><br><span class="line">    int result = size;</span><br><span class="line">    int specMode = MeasureSpec.getMode(measureSpec);</span><br><span class="line">    int specSize = MeasureSpec.getSize(measureSpec);</span><br><span class="line"></span><br><span class="line">    switch (specMode) &#123;</span><br><span class="line">    case MeasureSpec.UNSPECIFIED:</span><br><span class="line">        result = size;</span><br><span class="line">        break;</span><br><span class="line">    case MeasureSpec.AT_MOST:</span><br><span class="line">    case MeasureSpec.EXACTLY:</span><br><span class="line">        result = specSize;</span><br><span class="line">        break;</span><br><span class="line">    &#125;</span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>UNSPECIFIED据说一般是用于表示内部正处于测量的状态。在普通view中我们只要关注AT_MOST和EXACTLY。当view设置match_parent和具体大小时，是EXACTLY，wrap_content时是AT_MOST。为什么会是这样？可以看getChildMeasureSpec方法中各种情况。</p>
<p>所以当我们自定义view时，如果不处理AT_MOST情况，即wrap_content时，控件的大少就是父控件的大小。EXACTLY是可以正常被getDefaultSize处理的。</p>
<p>在ViewGroup中是没有重写onMeasure方法的，因为ViewGroup的大小还与ViewGroup的具体的布局特性有关。如LinearLayout和RelativeLayout的onMeasure不一样的。所以自定义ViewGroup时，要重写onMeasure方法。</p>
<p>但是，ViewGroup提供了测量子view的方法的，measureChildren和measureChildWithMargins，measureChild。</p>
<p>ViewGroup#measureChildren</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">    final int size = mChildrenCount;</span><br><span class="line">    final View[] children = mChildren;</span><br><span class="line">    for (int i = 0; i &lt; size; ++i) &#123;</span><br><span class="line">        final View child = children[i];</span><br><span class="line">        if ((child.mViewFlags &amp; VISIBILITY_MASK) != GONE) &#123;</span><br><span class="line">            measureChild(child, widthMeasureSpec, heightMeasureSpec);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ViewGroup#measureChild<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">protected void measureChild(View child, int parentWidthMeasureSpec,</span><br><span class="line">        int parentHeightMeasureSpec) &#123;</span><br><span class="line">    final LayoutParams lp = child.getLayoutParams();</span><br><span class="line"></span><br><span class="line">    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,</span><br><span class="line">            mPaddingLeft + mPaddingRight, lp.width);</span><br><span class="line">    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,</span><br><span class="line">            mPaddingTop + mPaddingBottom, lp.height);</span><br><span class="line"></span><br><span class="line">    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>ViewGroup#measureChildWithMargins</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">protected void measureChildWithMargins(View child,</span><br><span class="line">            int parentWidthMeasureSpec, int widthUsed,</span><br><span class="line">            int parentHeightMeasureSpec, int heightUsed) &#123;</span><br><span class="line">        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();</span><br><span class="line"></span><br><span class="line">        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,</span><br><span class="line">                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin</span><br><span class="line">                        + widthUsed, lp.width);</span><br><span class="line">        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,</span><br><span class="line">                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin</span><br><span class="line">                        + heightUsed, lp.height);</span><br><span class="line"></span><br><span class="line">        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>measureChild在measureChildren被循环遍历子view时调用。measureChildren和measureChildWithMargins的区别是，measureChildren是减去父控件的padding，而measureChildWithMargins减去了父控件的padding和view的margin。这直接影响了测量的大小是否包含了padding和margin。也就是view可以设置的最大大小是减去父控件的padding和view的内边距。</p>
<p>综上所述，在view中，就可以确定view的大小，提供了默认的onMeasure方法，但是默认的onMeasure方法不能正确处理AT_MOST（Wrap_content）的情况。在ViewGroup中，因为ViewGroup的具体大小和ViewGroup的布局特性有关，自定义ViewGroup要重写该方法。</p>
<h3 id="布局流程"><a href="#布局流程" class="headerlink" title="布局流程"></a>布局流程</h3><p>View#layout<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public void layout(int l, int t, int r, int b) &#123;</span><br><span class="line">    ...</span><br><span class="line">    </span><br><span class="line">    int oldL = mLeft;</span><br><span class="line">    int oldT = mTop;</span><br><span class="line">    int oldB = mBottom;</span><br><span class="line">    int oldR = mRight;</span><br><span class="line"></span><br><span class="line">    boolean changed = isLayoutModeOptical(mParent) ?</span><br><span class="line">            setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);</span><br><span class="line"></span><br><span class="line">    if (changed || (mPrivateFlags &amp; PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) &#123;</span><br><span class="line">        onLayout(changed, l, t, r, b);</span><br><span class="line"></span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在layout中分别调用了setFrame或者setOpticalFrame和onLayout。</p>
<p>setFrame或者setOpticalFrame中，赋值给mLeft，mTop，mRight，mBottom，确定了view的四个顶点，通过它们的get方法可以得到相应的值。这就确定了view在父控件中的位置坐标和view的宽和高。</p>
<p>View#onLayout是一个空实现。因为view只需要确定自己在父控件的位置即可。onLayout是用于在ViewGroup中确定子view的位置的。而onLayout的实现同样是与具体的ViewGroup的布局特性有关的。需要在自定义ViewGroup实现。</p>
<h3 id="绘制流程"><a href="#绘制流程" class="headerlink" title="绘制流程"></a>绘制流程</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">public void draw(Canvas canvas) &#123;</span><br><span class="line">       ...</span><br><span class="line"></span><br><span class="line">        /*</span><br><span class="line">         * Draw traversal performs several drawing steps which must be executed</span><br><span class="line">         * in the appropriate order:</span><br><span class="line">         *</span><br><span class="line">         *      1. Draw the background</span><br><span class="line">         *      2. If necessary, save the canvas&apos; layers to prepare for fading</span><br><span class="line">         *      3. Draw view&apos;s content</span><br><span class="line">         *      4. Draw children</span><br><span class="line">         *      5. If necessary, draw the fading edges and restore layers</span><br><span class="line">         *      6. Draw decorations (scrollbars for instance)</span><br><span class="line">         */</span><br><span class="line"></span><br><span class="line">        // Step 1, draw the background, if needed</span><br><span class="line">        int saveCount;</span><br><span class="line"></span><br><span class="line">        if (!dirtyOpaque) &#123;</span><br><span class="line">            drawBackground(canvas);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // skip step 2 &amp; 5 if possible (common case)</span><br><span class="line">        final int viewFlags = mViewFlags;</span><br><span class="line">        boolean horizontalEdges = (viewFlags &amp; FADING_EDGE_HORIZONTAL) != 0;</span><br><span class="line">        boolean verticalEdges = (viewFlags &amp; FADING_EDGE_VERTICAL) != 0;</span><br><span class="line">        if (!verticalEdges &amp;&amp; !horizontalEdges) &#123;</span><br><span class="line">            // Step 3, draw the content</span><br><span class="line">            if (!dirtyOpaque) onDraw(canvas);</span><br><span class="line"></span><br><span class="line">            // Step 4, draw the children</span><br><span class="line">            dispatchDraw(canvas);</span><br><span class="line"></span><br><span class="line">            drawAutofilledHighlight(canvas);</span><br><span class="line"></span><br><span class="line">            // Overlay is part of the content and draws beneath Foreground</span><br><span class="line">            if (mOverlay != null &amp;&amp; !mOverlay.isEmpty()) &#123;</span><br><span class="line">                mOverlay.getOverlayView().dispatchDraw(canvas);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // Step 6, draw decorations (foreground, scrollbars)</span><br><span class="line">            onDrawForeground(canvas);</span><br><span class="line">            ...</span><br><span class="line">        &#125;  </span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>draw过程就是主要就是，上面源码所说的那几个步骤。</p>
<p>1、如果需要背景，绘制背景<br>2、onDraw中，绘制自身<br>3、dispatchDraw中，绘制子view<br>4、onDrawForeground中绘制装饰</p>
<p>在自定义ViewGroup时，可以在dispatchDraw中遍历子view进行绘制。</p>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><p>布局</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span><br><span class="line">&lt;com.example.hyj.ht_test.widget.custom.CustomViewGroup</span><br><span class="line">    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</span><br><span class="line">    android:orientation=&quot;vertical&quot;</span><br><span class="line">    android:layout_width=&quot;match_parent&quot;</span><br><span class="line">    android:layout_height=&quot;match_parent&quot;&gt;</span><br><span class="line">    </span><br><span class="line">   &lt;com.example.hyj.ht_test.widget.custom.CustomViewGroup1</span><br><span class="line">        android:orientation=&quot;vertical&quot;</span><br><span class="line">        android:layout_width=&quot;match_parent&quot;</span><br><span class="line">        android:padding=&quot;10dp&quot;</span><br><span class="line">        android:layout_height=&quot;wrap_content&quot;&gt;</span><br><span class="line"></span><br><span class="line">       &lt;com.example.hyj.ht_test.widget.custom.CustomView</span><br><span class="line">           android:id=&quot;@+id/btn&quot;</span><br><span class="line">           android:background=&quot;@color/common_color&quot;</span><br><span class="line">           android:layout_margin=&quot;10dp&quot;</span><br><span class="line">           android:layout_width=&quot;match_parent&quot;</span><br><span class="line">           android:layout_height=&quot;wrap_content&quot;/&gt;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &lt;/com.example.hyj.ht_test.widget.custom.CustomViewGroup1&gt;</span><br><span class="line"></span><br><span class="line">&lt;/com.example.hyj.ht_test.widget.custom.CustomViewGroup&gt;</span><br></pre></td></tr></table></figure>
<p>CustomViewGroup1</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line">public class CustomViewGroup1 extends ViewGroup &#123;</span><br><span class="line"></span><br><span class="line">    private Context mContext;</span><br><span class="line"></span><br><span class="line">    private static final String TAG = &quot;CustomViewGroup&quot;;</span><br><span class="line"></span><br><span class="line">    ....构造函数...</span><br><span class="line"></span><br><span class="line">    public static class CustomLayoutParams extends MarginLayoutParams &#123;</span><br><span class="line"></span><br><span class="line">        public CustomLayoutParams(MarginLayoutParams source) &#123;</span><br><span class="line">            super(source);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public CustomLayoutParams(android.view.ViewGroup.LayoutParams source) &#123;</span><br><span class="line">            super(source);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public CustomLayoutParams(Context c, AttributeSet attrs) &#123;</span><br><span class="line">            super(c, attrs);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public CustomLayoutParams(int width, int height) &#123;</span><br><span class="line">            super(width, height);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成默认的布局参数</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    protected CustomLayoutParams generateDefaultLayoutParams() &#123;</span><br><span class="line">        return new CustomLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成布局参数</span><br><span class="line">     * 将布局参数包装成我们的</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) &#123;</span><br><span class="line">        return new CustomLayoutParams(p);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成布局参数</span><br><span class="line">     * 从属性配置中生成我们的布局参数</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) &#123;</span><br><span class="line">        return new CustomLayoutParams(getContext(), attrs);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">        //measureChildren(widthMeasureSpec, heightMeasureSpec);</span><br><span class="line"></span><br><span class="line">        int parentWidth = 0;</span><br><span class="line">        int parentHeight = 0;</span><br><span class="line">        int childCount = getChildCount();</span><br><span class="line">        if(childCount &gt; 0) &#123;</span><br><span class="line">            for (int i = 0; i &lt; childCount; i++) &#123;</span><br><span class="line">                View child = getChildAt(0);</span><br><span class="line">                measureChildWithMargins(child, widthMeasureSpec, 0,</span><br><span class="line">                        heightMeasureSpec, 0);</span><br><span class="line">                CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();</span><br><span class="line">                if (child.getVisibility() != View.GONE) &#123;</span><br><span class="line">                    parentWidth = getPaddingLeft() + getPaddingRight() +</span><br><span class="line">                            child.getMeasuredWidth() + clp.leftMargin + clp.rightMargin ;</span><br><span class="line">                    parentHeight = getPaddingTop() + getPaddingBottom() +</span><br><span class="line">                            child.getMeasuredHeight() + clp.topMargin + clp.bottomMargin;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        setMeasuredDimension(parentWidth, parentHeight);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onLayout(boolean changed, int l, int t, int r, int b) &#123;</span><br><span class="line"></span><br><span class="line">        int childCount = getChildCount();</span><br><span class="line">        int paddingTop = 0;</span><br><span class="line">        if(childCount &gt; 0) &#123;</span><br><span class="line">            for(int i = 0; i &lt; childCount; i++) &#123;</span><br><span class="line">                View child = getChildAt(i);</span><br><span class="line">                if(child.getVisibility() != View.GONE) &#123;</span><br><span class="line">                    int measuredHeight = child.getMeasuredHeight();</span><br><span class="line">                    int measuredWidth = child.getMeasuredWidth();</span><br><span class="line">                    CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();</span><br><span class="line">                    paddingTop = paddingTop + child.getPaddingTop();</span><br><span class="line">                    child.layout(getPaddingLeft() + clp.leftMargin,</span><br><span class="line">                            getPaddingTop() + clp.topMargin,</span><br><span class="line">                            getPaddingLeft() + clp.leftMargin + measuredWidth,</span><br><span class="line">                            getPaddingTop() + clp.leftMargin + measuredHeight);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>CustomViewGroup是默认的实现可以</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">public class CustomView extends View &#123;</span><br><span class="line"></span><br><span class="line">    public CustomView(Context context) &#123;</span><br><span class="line">        super(context);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public CustomView(Context context, @Nullable AttributeSet attrs) &#123;</span><br><span class="line">        super(context, attrs);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) &#123;</span><br><span class="line">        super(context, attrs, defStyleAttr);</span><br><span class="line">        init();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private void init() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;</span><br><span class="line">        setMeasuredDimension(getSize(600, widthMeasureSpec),</span><br><span class="line">                getSize(600, heightMeasureSpec));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private int getSize(int size, int measureSpec) &#123;</span><br><span class="line">        int result = 0;</span><br><span class="line">        int specMode = MeasureSpec.getMode(measureSpec);</span><br><span class="line">        int specSize = MeasureSpec.getSize(measureSpec);</span><br><span class="line">        if(specMode != MeasureSpec.EXACTLY) &#123;</span><br><span class="line">            result = size;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            result = specSize;</span><br><span class="line">        &#125;</span><br><span class="line">        return result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其实这些代码是<a href="https://zhangsunyucong.top/2018/01/10/android-event/">《Android的MotionEvent事件分发机制》</a>中用的代码基础上加的.</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
	  
		<!--MOB SHARE BEGIN-->
 <button id="rewardButton" class="-mob-share-open" style="margin-right:5px;">
    <span>分享</span>
  </button>
<div class="-mob-share-ui" style="display: none">
    <ul class="-mob-share-list">
        <li class="-mob-share-weibo"><p>新浪微博</p></li>
            <li class="-mob-share-tencentweibo"><p>腾讯微博</p></li>
            <li class="-mob-share-qzone"><p>QQ空间</p></li>
            <li class="-mob-share-qq"><p>QQ好友</p></li>
            <li class="-mob-share-weixin"><p>微信</p></li>
            <li class="-mob-share-douban"><p>豆瓣</p></li>
            <li class="-mob-share-renren"><p>人人网</p></li>
            <li class="-mob-share-kaixin"><p>开心网</p></li>
            <li class="-mob-share-facebook"><p>Facebook</p></li>
            <li class="-mob-share-twitter"><p>Twitter</p></li>
            <li class="-mob-share-pocket"><p>Pocket</p></li>
            <li class="-mob-share-google"><p>Google+</p></li>
            <li class="-mob-share-youdao"><p>有道云笔记</p></li>
    </ul>
    <div class="-mob-share-close">取消</div>
</div>
<div class="-mob-share-ui-bg"></div>
<script id="-mob-share" src="https://f1.webshare.mob.com/code/mob-share.js?appkey=230df6a994c78"></script>
<!--MOB SHARE END-->
      
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  
  
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="长孙雨聪--七星上将 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="长孙雨聪--七星上将 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
	  
	</div>

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    长孙雨聪--七星上将
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://zhangsunyucong.top/2018/01/15/view-meassure/" title="Androiod中View的工作原理">http://zhangsunyucong.top/2018/01/15/view-meassure/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/android/" rel="tag"><i class="fa fa-tag"></i> android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/10/android-event/" rel="next" title="Android的MotionEvent事件分发机制">
                <i class="fa fa-chevron-left"></i> Android的MotionEvent事件分发机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/18/android-wave-view/" rel="prev" title="自定义波纹WaveView">
                自定义波纹WaveView <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>

  
	  
	  
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/" class="site-author-image" rel="start" style="border:none">
              <img class="site-author-image" itemprop="image"
                src="/images/myphoto.jpg"
                alt="长孙雨聪--七星上将" />
			</a>	
            
              <p class="site-author-name" itemprop="name">长孙雨聪--七星上将</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zhangsunyucong?tab=repositories" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:969887864@qq.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wanandroid.com/" title="鸿洋_" target="_blank">鸿洋_</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://luodw.cc/" title="罗道文" target="_blank">罗道文</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://litten.me/" title="Litten" target="_blank">Litten</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://luuman.github.io" title="luuman" target="_blank">luuman</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.barretlee.com" title="小胡子哥" target="_blank">小胡子哥</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.halyul.cc" title="halyul" target="_blank">halyul</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/mine_song/article/details/64121769" title="剑指" target="_blank">剑指</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.ithmz.com/" title="奶爸大哥" target="_blank">奶爸大哥</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ruanyifeng.com" title="阮一峰" target="_blank">阮一峰</a>
                  </li>
                
              </ul>
			   
			   <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
	window.setTimeout("show_date_time()", 1000);
	BirthDay = new Date("11/24/2017 15:00:00");
	today  =new Date();
	timeold = (today.getTime()-BirthDay.getTime());
	sectimeold = timeold/1000
	secondsold = Math.floor(sectimeold);
	msPerDay = 24*60*60*1000
	e_daysold = timeold/msPerDay
	daysold = Math.floor(e_daysold);
	e_hrsold = (e_daysold-daysold)*24;
	hrsold = setzero(Math.floor(e_hrsold));
	e_minsold = (e_hrsold-hrsold)*60;
	minsold = setzero(Math.floor((e_hrsold-hrsold)*60));
	seconds = setzero(Math.floor((e_minsold-minsold)*60));
	document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
	if (i<10)
	{
		i="0" + i
	};
	return i;
}
show_date_time();
</script>

			  
            </div>
          

         
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#view的绘制流程是从哪里开始的？"><span class="nav-number">2.</span> <span class="nav-text">view的绘制流程是从哪里开始的？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MeasureSpec"><span class="nav-number">3.</span> <span class="nav-text">MeasureSpec</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MeasureSpec的创建和测量流程"><span class="nav-number">4.</span> <span class="nav-text">MeasureSpec的创建和测量流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#布局流程"><span class="nav-number">5.</span> <span class="nav-text">布局流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#绘制流程"><span class="nav-number">6.</span> <span class="nav-text">绘制流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例"><span class="nav-number">7.</span> <span class="nav-text">实例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">长孙雨聪--七星上将</span>
  
</div>

Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  







  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/canvas_lines.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytlJYAPJ';
      var conf = '72c4d5b62ad9725c5f533c23a6f1097e';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2YPqqc43cMkbPegNE3Auieo4-gzGzoHsz", "TVVsPYw3swS3SrByLqNtqlAL");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  
</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
